package ck.android.englishschool.thread;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import ck.android.englishschool.AppStatus;
import ck.android.englishschool.util.BrUtilManager;
import ck.android.englishschool.util.Const;
import ck.android.englishschool.util.JSONParser;
import ck.android.englishschool.util.ParameterUtil;
import ck.android.englishschool.vo.MemberVO;

public class LoginThread extends BaseThread{
	private MemberVO memberVo;
	
	public LoginThread(Context context
			, ThreadCallBack callback, MemberVO memberVo) {
		this.context = context;
		this.callBack = callback;
		this.appStatus = (AppStatus) context.getApplicationContext();
		this.memberVo = memberVo;
	}
	
	@Override
	public void run() {
		// 통신불통상태이면
		if(!appStatus.utilm.isNetworkConnected(context)) {
			callBack.threadCompleted(false, null, "통신 에러");
			return;
		}
		
		JSONParser jParser = new JSONParser();

		url = Const.MAIN_URL;
		post = ParameterUtil.getLoginPostParams(memberVo);
		
		JSONObject json = jParser.getJSONFromUrl(url, post);
		Log.i("url","url = " + url + post);
		Log.i("json","json = " + json);
		if(json == null) {
			callBack.threadError("데이터가 없습니다.");
			return;
		}

		try {
			int result = json.getInt(Const.RESULT);
			String message = json.getString(Const.MESSAGE);
			memberVo = new MemberVO();
			//정보를 못 가져 왔을때...
			if(result == 0){
				appStatus.setMemberVo(memberVo);
				callBack.threadError(message);
			}
			//정보를 가져 왔을때...
			else{
				JSONArray jArray = json.getJSONArray(Const.DATA);
				for(int i=0; i <jArray.length(); i++){
					JSONObject itemObject = jArray.getJSONObject(i);
					System.out.println("뭐들었어??->"+itemObject.toString());
					memberVo.setMemSeq(BrUtilManager.isNullCheck(appStatus.utilm.getStringJSONObject(itemObject, MemberVO.MEMSEQ)));
					memberVo.setUserId(BrUtilManager.isNullCheck(appStatus.utilm.getStringJSONObject(itemObject, MemberVO.USERID)));
					memberVo.setUserPass(BrUtilManager.isNullCheck(appStatus.utilm.getStringJSONObject(itemObject, MemberVO.USERPASS)));
				}
				appStatus.setMemberVo(memberVo);
				callBack.threadCompleted(true, memberVo, message);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}
